package com.superatom.springframework.core.type.filter;

import com.superatom.springframework.lang.Nullable;
import com.superatom.springframework.util.ClassUtils;

/**
 * @author Kwokchiu Wong
 * @Title:
 * @Package
 * @Description:
 * @date 2020/10/19 5:15 下午
 */
public class AssignableTypeFilter extends AbstractTypeHierarchyTraversingFilter {

    private final Class<?> targetType;


    /**
     * Create a new AssignableTypeFilter for the given type.
     * @param targetType the type to match
     */
    public AssignableTypeFilter(Class<?> targetType) {
        super(true, true);
        this.targetType = targetType;
    }

    /**
     * Return the {@code type} that this instance is using to filter candidates.
     * @since 5.0
     */
    public final Class<?> getTargetType() {
        return this.targetType;
    }

    @Override
    protected boolean matchClassName(String className) {
        return this.targetType.getName().equals(className);
    }

    @Override
    @Nullable
    protected Boolean matchSuperClass(String superClassName) {
        return matchTargetType(superClassName);
    }

    @Override
    @Nullable
    protected Boolean matchInterface(String interfaceName) {
        return matchTargetType(interfaceName);
    }

    @Nullable
    protected Boolean matchTargetType(String typeName) {
        if (this.targetType.getName().equals(typeName)) {
            return true;
        }
        else if (Object.class.getName().equals(typeName)) {
            return false;
        }
        else if (typeName.startsWith("java")) {
            try {
                Class<?> clazz = ClassUtils.forName(typeName, getClass().getClassLoader());
                return this.targetType.isAssignableFrom(clazz);
            }
            catch (Throwable ex) {
                // Class not regularly loadable - can't determine a match that way.
            }
        }
        return null;
    }

}
